// pages/autocar/useddetail.js
var util = require('../../utils/util.js');
let wxparse = require("../../wxParse/wxParse.js");
const app = getApp();
var clickflag = 1;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    cid: 0,
    carinfo: [],
    imgArrs: [],
    showModalStatus: false,
    showTopTips: false,
    errorMsg: '',
    mobile: '',
    buyname: '',
    banner: '',
    cartype: '',
    storename: '',
    cid: 0,
    submitname: '看真车',
    radioItems: [
      { name: '不需要', value: '0', checked: true },
      { name: '需要　', value: '1' }
    ],
    isjs: 0,
    times: ["上午:10:00~12:00", "下午:14:00~18:00"],
    timeIndex: 0,
    dates: ["2019-10-23", "2019-10-24", "2019-10-25"],
    dateIndex: 0,
    planb:false,
    showModalAuth: false,
    animationData: '',
    isLoginAuth: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (!app.globalData.isLoginAuth) {
      this.showModal();
    }
    this.getdatelist();
    this.setData({
      cid: options.cid,
      isLoginAuth: app.globalData.isLoginAuth
    });
    var that = this;
    var upuid = options.cfuid;
    if (parseInt(upuid) > 0) {
      wx.setStorageSync('upuid', upuid);
    }
    wx.request({
      url: app.globalData.hostUrl + 'handler/getCarsdetail',
      data: {
        cid: that.data.cid
      },
      success: function (res) {
        //   console.log(res);
        if (res.data.code == 200) {
          that.setData({
            carinfo: res.data.result,
            banner: res.data.result.bannername,
            cartype: res.data.result.lvlname,
            storename: res.data.result.storeinfo.sname,
            imgArrs: res.data.result.imgarr,
            planb: res.data.result.moneypay2=='0.00'?true:false,
          })
        }
        else if (res.data.code == 201) {
          wx.showToast({
            title: '参数错误',
            icon: 'error',
            duration: 2000
          })
        }
       // wxparse.wxParse('content', 'html', res.data.result.desc, that, 5);
      }
    })
  },
  getdatelist: function () {
    var dataArr = [];
    for (var i = 1; i < 4; i++) {
      var date = new Date();
      var nexttime = date.getTime() + i * 24 * 60 * 60 * 1000;
      date.setTime(nexttime);

      var year = date.getFullYear();
      var month = date.getMonth() + 1
      var day = date.getDate();
      var datename = year + "-" + month + "-" + day;

      dataArr.push(datename);
    }
    this.setData({
      dates: dataArr
    });
  },  
  dateChange: function (e) {
    this.setData({
      dateIndex: e.detail.value
    })
  },
  timeChange: function (e) {
    this.setData({
      timeIndex: e.detail.value
    })
  },
  radioChange: function (e) {
    var radioItems = this.data.radioItems;
    for (var i = 0, len = radioItems.length; i < len; ++i) {
      radioItems[i].checked = radioItems[i].value == e.detail.value;
    }

    this.setData({
      radioItems: radioItems,
      isjs: e.detail.value
    });

  },
  previewImage: function (e) {
    var imgfiles = null;
    var index = e.currentTarget.dataset.index; //获取当前长按图片下标
    imgfiles = this.data.imgArrs;

    var imgurl = [imgfiles[index]];
    wx.previewImage({
      current: e.currentTarget.id, // 当前显示图片的http链接
      urls: imgurl // 需要预览的图片http链接列表
    })
  },
  getbuyname: function (e) {
    console.log(e)
    this.setData({
      buyname: e.detail.value
    });
  },
  getmobile: function (e) {
    this.setData({
      mobile: e.detail.value
    });
  },
  calling: function (e) {
    var mobile = '15916351997';
    wx.makePhoneCall({
      phoneNumber: mobile,
      success: function () {
        //console.log("拨打电话成功！")
      },
      fail: function () {
        // console.log("拨打电话失败！")
      }
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },
  // 弹框
  openEdit: function (e) {
    console.log(e);
    this.setData({
      showModalStatus: true,
      cid: e.currentTarget.dataset.cid
    });
    util.clearError(this);
  },
  //關閉
  closeEdit: function (e) {
    this.setData({
      showModalStatus: false
    });
    util.clearError(this);
  },
  yyApply: function (e) {
    var that = this;
    var name = this.data.buyname;
    var mobile = this.data.mobile;
    var cid = this.data.cid;

    if (name == '') {
      util.isError("请填写您的称呼", that);
      return false;
    }
    var myreg = /^(14[0-9]|13[0-9]|15[0-9]|17[0-9]|18[0-9])\d{8}$$/;
    if (mobile == '') {
      util.isError("请填写手机号码", that);
      return false;
    }
    else if (!myreg.test(mobile)) {
      util.isError("请输入正确的手机号!", that);
      return false;
    }
    var postdata = {
      'name': name,
      'phone': mobile,
      'banner': that.data.banner,
      'cartype': that.data.cartype,
      'storename': that.data.storename,
      'carid': cid,
      'uid': wx.getStorageSync('userId'),
      'flag': 2,
      'formid': e.detail.formId,
      'openid': wx.getStorageSync('openId'),
      'plandate': this.data.dates[this.data.dateIndex],
      'ampm': this.data.times[this.data.timeIndex],
      'isjs': this.data.isjs,
    };
    //console.log(postdata);
    var requrl = app.globalData.hostUrl + 'handler/buycarOrder';
    if (clickflag == 1) {
      clickflag = 0;
      wx.request({
        url: requrl,
        data: postdata,
        header: {
          'Content-Type': 'application/x-www-form-urlencoded',
          'grant-appid': app.globalData.appid
        },
        method: 'POST',
        success: function (res) {
//          console.log(res);
          if (res.data.code == 200) {
            wx.showModal({
              title: '提示',
              content: '提交成功!',
              success: function (res) {
                that.closeEdit();
                wx.navigateTo({
                  url: '../autocar/usedcar',
                })
              }
            });
          }
          else {
            util.isError(res.data.result, that);
          }
          clickflag = 1;
        }
      })
    }
  },
  onShareAppMessage: function () {
    var that = this;
    if (res.from === 'button') {
      // 来自页面内转发按钮<button open-type="share">分享名片</button>
    }
    var shearinfo = {
      title: that.data.carinfo['cartitle'],
      path: 'pages/autocar/useddetail?cid=' + that.data.cid + '&cfuid=' + wx.getStorageSync('userId')
    };
    return shearinfo;
  },
  showModal: function () {
    // 显示遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "ease-in-out",
      delay: 0
    })
    this.animation = animation
    animation.translateY(500).step()
    this.setData({
      animationData: animation.export(),
      showModalAuth: true
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export()
      })
    }.bind(this), 200)
  },
  hideModal: function () {
    this.setData({
      showModalAuth: false,
    })
  },
  bindGetUserInfo: function (e) {
    console.log(e);
    if (e.detail.errMsg == 'getUserInfo:ok') {
      app.globalData.userInfo = e.detail.userInfo;
      app.getfansinfo();
    }
    else if (e.detail.errMsg == "getUserInfo:fail auth deny") {

    }
    else {
      wx.redirectTo({
        url: '../xuecar/index',
      })
    }
  }
})